<?php
/**
 * Created by PhpStorm.
 * User: ZhengYaFeng
 * Date: 2016/10/17
 * Time: 15:27
 */
namespace App\Http\Controllers\Admin\AdminUser;

use App\Http\Controllers\AdminController;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreAdminiUserGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminiUserGroupController extends AdminController
{
    /**
     * 用户组列表页...
     * @author  <ZhengYaFeng>
     * @data    <2016-10-18 11:32>
     * @access  <public>
     * @return  <view>
     * @des     <描述:用户组列表页>
     * @return mixed
     */
    public function index()
    {
        $data = array();
        $data = $this->getList('index',$data);
        return \Helpers::showViewCURD('Admin.AdminUserGroup.index',3,'',$data);
    }

    /**
     * 公共获取列表数据方法...
     * @author  <ZhengYaFeng>
     * @data    <2016-10-18 11:32>
     * @return  <view>
     * @des     <描述:公共获取列表数据方法>
     * @param string $flag
     * @param $data
     * @return array <$data>
     */
    public function getList($flag='index',$data)
    {
        $selectId = $flag == 'rb' ? 2 : 1;
        //获取所属父级别字典
        $res = DB::select('
                        select a.name,a.id,a.pid,b.name as pidname,concat(a.path,",",a.id) as bpath
                        from wj_admini_group a 
                        left join wj_admini_group b 
                        on a.pid = b.id 
                        where a.is_del = ? 
                        order by bpath 
                ',[$selectId]);
        //生成公共处理前格式
        $data['list'] = empty($res) ? '' : json_encode($res);
        //公共处理数据给页面
        $data['list'] = json_decode($data['list'],true);
        return $data;
    }

    /**
     * 用户组新增页面...
     * @author  <ZhengYaFeng>
     * @data    <2016-10-18 11:32>
     * @access  <public>
     * @return  <view>
     * @des     <描述:用户组新增页面>
     * @return mixed
     */
    public function create()
    {
        $data = array();
        $data = $this->getCreateOrEditD($data, 'arr');
        return \Helpers::showViewCURD('Admin.AdminUserGroup.create', 1, '新增', $data);
    }

    /**
     * 新增或修改页面表单数据公共查询...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-18 11:32>
     * @des     <描述:新增或修改页面表单数据公共查询...>
     * @param   <array>     <$data>         [返回数据源]
     * @param   <string>    <$strOrArr>     [下拉生成数据为下拉字符串或者数组]
     * @return  <array>     <$data>         [返回数据数组]
     */
    public function getCreateOrEditD($data,$strOrArr='str')
    {
        //获取所属父级别字典
        $where = array('is_del'=>array('sb'=>'=','v'=>1));
        $pidListRes =\Helpers::DbForTree('admini_group','','id,pid,path,name,concat(path,\',\',id) as bpath',$where,'bpath');
        //生成所属父级栏目下拉字符串
        $data['pidListStr'] = \Helpers::createTreeSelect($pidListRes,$strOrArr,array('id'=>'id','pid'=>'pid','path'=>'path','title'=>'name'));
        return $data;
    }

    /**
     * 用户组新增操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <2016-10-18 11:32>
     * @des     <描述:用户组新增操作>
     * @param   StoreAdminiUserGroup    $request
     * @return  <array> <errorMsg>
     */
    public function store(StoreAdminiUserGroup $request)
    {
        //验证post提交
        if($request->isMethod('post'))
        {
            $post = $request->all();
            $inserArr = $this->addOrEditFormatD($post);
            //入库
            $res = DB::table('admini_group')->insertGetId($inserArr);
            $errors = $res ? '新增成功!' : '新增失败!';
            $isSuccess = $res ? 'success' : 'error';
            \Helpers::insertUserActionLog('rbacGroup','add',$res,$isSuccess,$inserArr);
            return redirect()->back()->withErrors($errors);
        }else{
            abort(404);
        }
    }

    /**
     * 公共的新增或修改处理表单数据...
     * @author  <ZhengYaFeng>
     * @data    <2016-10-18 11:32>
     * @access  <public>
     * @des     <描述:公共的新增或修改处理表单数据>
     * @param $request
     * @param string $addOrEdit
     * @return mixed
     */
    public function addOrEditFormatD($request,$addOrEdit='add')
    {
        //数据处理
        $pid = explode('_',$request['pid']);
        $addOrEditArr['pid'] = !empty($pid[0]) ? $pid[0] : 0;
        $addOrEditArr['path'] = !empty($pid[0]) && $pid[1] != '' ? $pid[1].','.$pid[0] : 0;
        $addOrEditArr['name'] = $request['name'];
        $addOrEditArr['description'] = !empty($request['description']) ? $request['description'] : '';
        $addOrEditTimeK = $addOrEdit == 'edit' ? 'update_time' : 'create_time';
        $addOrEditArr[$addOrEditTimeK] = time();
        $addOrEditArr['is_del'] = 1;
        $admin_id = json_decode(session('Z_AdminiUser'),true);
        $addOrEditArr['admin_id'] = !empty($admin_id['id']) ? $admin_id['id'] : '';
        return $addOrEditArr;
    }

    /**
     * 修改页面...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @des     <描述:修改页面>
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        //验证数据
        if(empty($id)) abort(404);
        $data = array();
        $data = $this->getCreateOrEditD($data,'arr');
        $data['editList'] = DB::table('admini_group')->where('id',$id)->first();
        return \Helpers::showViewCURD('Admin.AdminUserGroup.create',2,'修改',$data);
    }

    /**
     * 修改操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @des     <描述:修改操作>
     * @param $id
     * @param StoreAdminiUserGroup $request
     * @return $this
     */
    public function update($id,StoreAdminiUserGroup $request)
    {
        if(empty($id)) abort(404);
        //修改数据处理
        $editArr = $this->addOrEditFormatD($request,'edit');
        $res = DB::table('admini_group')
            ->where('id',intval($id))
            ->update($editArr);
        //根据入库结果返回状态
        $errors = $res ? '修改成功!' : '修改失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacGroup','up',$id,$isSuccess,$editArr);
        return redirect()->back()->withErrors($errors);
    }

    /**
     * 删除操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:删除操作>
     * @param $id
     * @return string
     */
    public function del($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac'])) abort(404);
        $status = $_POST['ac'];
        //逻辑删除或者物理删除验证是否存在下级,无下级可执行下一步
        //检测当前数据是否存在下级,有下级必须删除下级后才能删除上级
        $hasChildren = DB::table('admini_group')->where('is_del',$status)->where('pid',$id)->first();
        if($hasChildren) die(json_encode(array('error'=>-1,'msg'=>'当前数据存在子集分类,请删除后再试!')));
        //status:1.逻辑删除数据,2.物理删除数据
        if($status == 1) $res = DB::table('admini_group')->where('id',intval($id))->update(array('is_del'=>2));
        if($status == 2) $res = DB::table('admini_group')->where('id',intval($id))->delete();
        $preMsg = '删除';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacGroup','del',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 还原数据...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:还原数据>
     * @param $id
     * @return string
     */
    public function back($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac'])) abort(404);
        //还原逻辑删除数据
        $res = DB::table('admini_group')->where('id',intval($id))->update(array('is_del'=>1));
        $preMsg = '还原';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacGroup','back',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 回收站...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:>
     * @return mixed
     */
    public function rb()
    {
        $data = array();
        $data = $this->getList('rb',$data);
        return \Helpers::showViewCURD('Admin.AdminUserGroup.index',4,'',$data);
    }

    public function set($id,Request $request)
    {
        if(empty($id)) abort(404);
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            $post = $request->all();
            $group_id = $id;
            //删除权限节点
            DB::delete('delete from wj_admini_group_node where group_id = ?',[$group_id]);
            //赋予权限节点
            if(!empty($post['node_check']))
            {
                foreach($post['node_check'] as $v)
                {
                    DB::insert('insert into wj_admini_group_node (group_id, node_id) values (?, ?)', [$group_id, $v]);
                }
            }

            \Helpers::insertUserActionLog('rbacGroup','setNode',$id,'success',$post);
            return redirect()->back()->withErrors('设置成功!');
        }
        $data = array();
        $data['setNodeData'] = $this->setNodeData($id);
        $data['id'] = $id;
        return view('Admin.AdminUserGroup.set')->withData($data);
    }

    private function setNodeData($id)
    {
        if(empty($id)) return;
        //节点数据
        $list = DB::select('
                        select id,pid,path,name,concat(path,",",id) as bpath 
                        from wj_admini_node 
                        where is_del = ? 
                        order by bpath
                    ',[1]);
        //当前用户组权限数据
        $group_node = DB::select('
                            select node_id 
                            from wj_admini_group_node 
                            where group_id = ?
                        ',[$id]);
        $node = array();
        foreach ($group_node as $k1 => $v1)
        {
            $node[] = $v1->node_id;
        }
        $str = '';
        if(!empty($list))
        {
            foreach($list as $k => $v){
                $str .= '<div style="margin-top:5px;">';
                if(!empty($v->path)){
                    $count_num = count(explode(',',$v->path));
                    for($i = 0;$i < $count_num;$i++){
                        $str.= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    }
                    if(!empty($group_node) && in_array($v->id,$node)){
                        $str .= '<input type="checkbox" name="node_check[]" id_n="'.$v->id.'" pid = "'.$v->pid.'" checked="checked" value = "'.$v->id.'">&nbsp;<b >'.$v->name.'</b></div>';
                    }else{
                        $str .= '<input type="checkbox" name="node_check[]" id_n="'.$v->id.'" pid = "'.$v->pid.'" value = "'.$v->id.'">&nbsp;<b >'.$v->name.'</b></div>';
                    }
                }else{
                    if(!empty($group_node) && in_array($v->id,$node)){
                        $str .= '<input type="checkbox" name="node_check[]" id_n="'.$v->id.'" pid = "'.$v->pid.'" checked="checked" value = "'.$v->id.'">&nbsp;<b >'.$v->name.'</b></div>';
                    }else{
                        $str .= '<input type="checkbox" name="node_check[]" id_n="'.$v->id.'" pid = "'.$v->pid.'" value = "'.$v->id.'">&nbsp;<b >'.$v->name.'</b></div>';
                    }
                }
            }
        }
        return $str;
    }
}